package cn.xiuxius.embedded.util;

import java.nio.charset.StandardCharsets;

public class MessageUtil {

    // 将字符串编码为 UTF-8 后返回其二进制表示（原始字节）
    public static byte[] stringToHex(String data) {
        return data.getBytes(StandardCharsets.UTF_8);
    }

    public static byte[] stringAsHex(String data) {
        // 只保留0-9、a-f、A-F
        String hex = data.replaceAll("[^0-9A-Fa-f]", "");

        // 如果是奇数长度，去掉最后一个字符
        if (hex.length() % 2 != 0) {
            hex = hex.substring(0, hex.length() - 1);
        }

        int len = hex.length() / 2;
        byte[] result = new byte[len];

        for (int i = 0; i < len; i++) {
            String byteStr = hex.substring(i * 2, i * 2 + 2);
            result[i] = (byte) Integer.parseInt(byteStr, 16);
        }

        return result;
    }


    // 将 UTF-8 编码的字节数组解码为字符串
    public static String bytesToString(byte[] data) {
        return new String(data, StandardCharsets.UTF_8);
    }

    // 将字节数组转为大写十六进制字符串，例如 [0xFF, 0x00, 0xA1] -> "FF00A1"
    //切割
    public static String bytesAsString(byte[] data) {
        StringBuilder hexBuilder = new StringBuilder();
        for (byte b : data) {
            hexBuilder.append(String.format("%02X", b));
        }

        StringBuilder formattedBuilder = new StringBuilder();
        String hexString = hexBuilder.toString();

        for (int i = 0; i < hexString.length(); i++) {
            if (i > 0 && i % 2 == 0) {
                formattedBuilder.append(" ");
            }
            formattedBuilder.append(hexString.charAt(i));
        }

        return formattedBuilder.toString();
    }
}
